﻿using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.API.Dtos;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Interface;
using MediatR;
using SqlSugar;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class GetCodePinkingOrderHandler : IRequestHandler<GetCodePinkingOrderCommand, APIResult<List<PinkingOrderDto>>>
    {
        private readonly IBaseRepository<PickingModel> pickingRepo;
        private readonly IBaseRepository<OutboundRecordModel> outBoundRepo;

        public GetCodePinkingOrderHandler(IBaseRepository<PickingModel> pickingRepo,
                                          IBaseRepository<OutboundRecordModel> outBoundRepo)
        {
            this.pickingRepo = pickingRepo;
            this.outBoundRepo = outBoundRepo;
        }
        public Task<APIResult<List<PinkingOrderDto>>> Handle(GetCodePinkingOrderCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<PinkingOrderDto>> result = new APIResult<List<PinkingOrderDto>>();
            var bound = outBoundRepo.GetAll().FirstOrDefault(x => x.PickFormCode == request.PickFormCode);
            if (bound == null) 
            {
                result.Message = "找不到此领料单信息";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var pick = pickingRepo.GetAll().Where(x=>x.PickFormCode==bound.PickFormCode).ToList();
            PinkingOrderDto orderDtos = new PinkingOrderDto()
            {
                PickFormCode = bound.PickFormCode,
                DispatchCode = bound.DispatchCode,
                PickDate = bound.PickDate,
                Picker = bound.Picker,
                PickFormName = bound.PickFormName,
                PickInfo = bound.PickInfo,
                ProductionOrdersCode = bound.ProductionOrdersCode,
                Picks = pick,
            };
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.Data = new List<PinkingOrderDto> { orderDtos }; ;
            return Task.FromResult(result);
        }
    }
}
